package com.presto.directo.mvvm.view

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.webkit.*
import com.presto.directo.base.BaseActivity
import com.presto.directo.databinding.ActivityWebBinding

class WebActivity : BaseActivity() {

    private val binding by lazy { ActivityWebBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val url = intent.getStringExtra("url") ?: ""
        val title = intent.getStringExtra("title") ?: ""
        binding.webView.settings.useWideViewPort = true
        binding.webView.settings.loadsImagesAutomatically = true
        binding.webView.settings.cacheMode = WebSettings.LOAD_NO_CACHE
        binding.webView.settings.setAppCacheEnabled(false)
        binding.webView.settings.javaScriptEnabled = true
        binding.webView.settings.domStorageEnabled = true
        binding.webView.settings.loadWithOverviewMode = true
        binding.webView.settings.setSupportZoom(true)
        binding.webView.settings.builtInZoomControls = true
        binding.webView.settings.displayZoomControls = false
        binding.webView.settings.textZoom = 100
        binding.webView.settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        binding.webView.removeJavascriptInterface("searchBoxJavaBridge_") // 修复漏洞
        binding.titleBar.title = title
        binding.webView.loadUrl(url)
        binding.webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                if (newProgress == 100) {
                    binding.progress.visibility = View.GONE
                } else {
                    binding.progress.visibility = View.VISIBLE
                    binding.progress.progress = newProgress
                }
                super.onProgressChanged(view, newProgress)
            }
        }
        binding.webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                if (url.isNullOrBlank() || !url.startsWith("http") && !url.startsWith("ftp")) {
                    runCatching {
                        val action = when {
                            url.startsWith("tel") -> Intent.ACTION_DIAL
                            else -> Intent.ACTION_VIEW
                        }
                        startActivity(Intent(action, Uri.parse(url)))
                    }
                    return true
                }
                return false
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.webView.removeAllViews()
        binding.webView.destroy()
    }

    override val rootView: View
        get() = binding.root
}